import NProgress from '@/utils/progress'
import type { AppRouteRecordRaw } from '/#/router'
import { createRouter, Router, RouteRecordRaw } from 'vue-router'
import { getConfig } from '@/config'
import { getHistoryMode } from '@/utils'
import { $t, transformI18n } from '@/i18n'

// 根路由
export const ROOT_ROUTE: AppRouteRecordRaw = {
  path: '/',
  name: 'Root',
  meta: {
    title: $t('menus.home'),
    breadcrumbHidden: true,
  },
}

// login on a page
export const LOGIN_ROUTE: AppRouteRecordRaw = {
  path: '/login',
  name: 'Login',
  component: () => import('~/src/views/login/index.vue'),
  meta: {
    title: $t('menus.login'),
  },
}

// 404 on a page
export const PAGE_NOT_FOUND_ROUTE: AppRouteRecordRaw = {
  path: '/:path(.*)*',
  name: 'PageNotFound',
  meta: {
    title: $t('menus.errorPage'),
    breadcrumbHidden: true,
    hidden: true,
  },
  children: [
    {
      path: '/:path(.*)*',
      name: 'PageNotFound',
      component: () => import('@/views/error/404.vue'),
      meta: {
        title: $t('menus.pageNotFound'),
        breadcrumbHidden: true,
        hidden: true,
      },
    },
  ],
}

// 未经许可的基本路由
export const constantRoutes: AppRouteRecordRaw[] = [LOGIN_ROUTE, PAGE_NOT_FOUND_ROUTE]

/** 路由白名单 */
const routesWhiteList = ['/login']

/** 创建路由实例 */
const router: Router = createRouter({
  history: getHistoryMode(),
  routes: constantRoutes as RouteRecordRaw[],
  // 是否应该禁止尾部斜杠。默认为false
  strict: true,
  scrollBehavior(to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        return savedPosition
      } else {
        if (from.meta.saveSrollTop) {
          const top: number = document.documentElement.scrollTop || document.body.scrollTop
          resolve({ left: 0, top })
        }
      }
    })
  },
})

/** 权限认证 */
function setupPermissions(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start()
    to.matched.some((item) => {
      if (!item.meta.title) return ''
      const Title = getConfig().Title
      if (Title) document.title = `${transformI18n(item.meta.title)} | ${Title}`
      else document.title = transformI18n(item.meta.title)
    })
    // 暂时设置为未登录
    const hasToken = false
    if (hasToken) {
    } else {
      if (to.path !== '/login') {
        if (routesWhiteList.includes(to.path)) {
          next()
        } else {
          next({ path: '/login', replace: true })
        }
      } else {
        next()
      }
    }
  })
  router.afterEach(async (to: any) => {
    if (NProgress.status) NProgress.done()
  })
}

/** 加载路由配置 */
export const setupRouter = (app: any) => {
  setupPermissions(router)
  app.use(router)
  return router
}

export default router
